package com.fds.demo.alipay.service;

import com.alipay.api.AlipayApiException;
import com.fds.demo.alipay.config.AliPayConf;
import com.fds.demo.alipay.config.AliPayNotify;
import com.fds.demo.alipay.config.AliPayNotifyResult;
import com.fds.demo.alipay.config.AliPcPayParam;
import com.fds.demo.alipay.utils.AliPayUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

/**
 * @author: fds
 * @date: 2019/11/1
 * @description: 支付宝支付service
 */
@Service
public class AliPayServiceImpl {

    /**
     * 注入 日志.
     */
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AliPayServiceImpl.class);

    /**
     * 支付配置文件.
     */
    @Autowired
    private AliPayConf aliPayConf;

    /**
     * pc支付service.
     * @param response 响应体，返回form表单数据
     * @throws AlipayApiException
     * @throws IOException
     */
    public void pcPay(final HttpServletResponse response, final String orderNo)
            throws AlipayApiException, IOException {

        AliPcPayParam aliPcPayParam = new AliPcPayParam();
        aliPcPayParam.setOutTradeNo(UUID.randomUUID().toString());
        aliPcPayParam.setTotalAmount("0.01");
        aliPcPayParam.setSubject("测试支付宝");
        if (null == aliPcPayParam) {
            response.setContentType("text/html;charset=utf-8");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("参数错误");
            response.getWriter().flush();
            response.getWriter().close();
        }
        AliPayUtils.pcPay(response, aliPayConf, aliPcPayParam);
    }

    /**
     * 异步通知解析.
     * @param request
     * @return String (成功返回 success 字符串，支付宝就不会在调用了；不然会重复通知8次)
     * @throws AlipayApiException
     */
    public String notifyUrl(final HttpServletRequest request) throws AlipayApiException {
        AliPayNotify aliPayNotify = new AliPayNotify();
        return aliPayNotify.validSuccess(request, aliPayConf, new AliPayNotifyResult() {
            @Override
            public String paySuccess(Map<String, String> result) {
                LOGGER.info("异步通知成功；支付成功");
                // 订单号；
                // 获取订单号
                String outTradeNo = result.get("out_trade_no");
                BigDecimal price = new BigDecimal(result.get("total_amount"));
                return "success";
            }

            @Override
            public void payFail(Map<String, String> result) {
                LOGGER.info("异步通知成功；支付失败");
            }

            @Override
            public void verifyFail(Map<String, String> result) {
                LOGGER.error("验签失败");
            }
        });
    }
}
